<!DOCTYPE html>
<html
  lang="zh"
  xmlns:th="http://www.thymeleaf.org"
  xmlns:shiro="http://www.pollix.at/thymeleaf/shiro"
>
  <head>
    <th:block th:include="include :: header('学习视频列表')" />
  </head>
  <body class="gray-bg">
    <div class="container-div">
      <div class="row">
        <div class="col-sm-12 search-collapse">
          <form id="formId">
            <div class="select-list">
              <ul>
                <li>
                  <label>视频标题：</label>
                  <input type="text" name="title" />
                </li>
                <li>
                  <label>分类：</label>
                  <input type="text" name="category" />
                </li>
                <li>
                  <label>状态：</label>
                  <select name="status">
                    <option value="">所有</option>
                    <option value="1">启用</option>
                    <option value="0">禁用</option>
                  </select>
                </li>
                <li>
                  <a
                    class="btn btn-primary btn-rounded btn-sm"
                    onclick="$.table.search()"
                    ><i class="fa fa-search"></i>&nbsp;搜索</a
                  >
                  <a
                    class="btn btn-warning btn-rounded btn-sm"
                    onclick="$.form.reset()"
                    ><i class="fa fa-refresh"></i>&nbsp;重置</a
                  >
                </li>
              </ul>
            </div>
          </form>
        </div>

        <div class="btn-group-sm" id="toolbar" role="group">
          <a
            class="btn btn-success"
            onclick="$.operate.add()"
            shiro:hasPermission="dj:study:video:add"
          >
            <i class="fa fa-plus"></i> 新增
          </a>
          <a
            class="btn btn-primary single disabled"
            onclick="$.operate.edit()"
            shiro:hasPermission="dj:study:video:edit"
          >
            <i class="fa fa-edit"></i> 修改
          </a>
          <a
            class="btn btn-danger multiple disabled"
            onclick="$.operate.removeAll()"
            shiro:hasPermission="dj:study:video:remove"
          >
            <i class="fa fa-remove"></i> 删除
          </a>
          <a
            class="btn btn-warning"
            onclick="$.table.exportExcel()"
            shiro:hasPermission="dj:study:video:export"
          >
            <i class="fa fa-download"></i> 导出
          </a>
        </div>
        <div class="col-sm-12 select-table table-striped">
          <table id="bootstrap-table"></table>
        </div>
      </div>
    </div>
    <th:block th:include="include :: footer" />
    <script th:inline="javascript">
      var editFlag = [[${@permission.hasPermi('dj:study:video:edit')}]];
      var removeFlag = [[${@permission.hasPermi('dj:study:video:remove')}]];
      var prefix = ctx + "dj/study/video";

      $(function() {
      	var options = {
      		url: prefix + "/list",
      		createUrl: prefix + "/add",
      		updateUrl: prefix + "/edit/{id}",
      		removeUrl: prefix + "/remove",
      		exportUrl: prefix + "/export",
      		modalName: "学习视频",
      		columns: [{
      			checkbox: true
      		},
      		{
      			field: 'id',
      			title: '视频ID'
      		},
      		{
      			field: 'title',
      			title: '视频标题'
      		},
      		{
      			field: 'coverUrl',
      			title: '封面图片',
      			formatter: function(value, row, index) {
      				if (value) {
      					return '<img src="' + value + '" style="width:100px;height:60px;" />';
      				} else {
      					return '无封面';
      				}
      			}
      		},
      		{
      			field: 'duration',
      			title: '视频时长(秒)'
      		},
      		{
      			field: 'category',
      			title: '分类'
      		},
      		{
      			field: 'viewCount',
      			title: '观看次数'
      		},
      		{
      			field: 'status',
      			title: '状态',
      			align: 'center',
      			formatter: function(value, row, index) {
      				if (value == 1) {
      					return '<span class="badge badge-primary">启用</span>';
      				} else {
      					return '<span class="badge badge-danger">禁用</span>';
      				}
      			}
      		},
      		{
      			field: 'createTime',
      			title: '创建时间'
      		},
      		{
      			title: '操作',
      			align: 'center',
      			formatter: function(value, row, index) {
      				var actions = [];
      				if (row.status == 1 && row.videoUrl) {
      					actions.push('<a class="btn btn-info btn-xs" href="javascript:void(0)" onclick="playVideo(\'' + row.videoUrl + '\', ' + row.id + ')"><i class="fa fa-play"></i>播放</a> ');
      				}
      				actions.push('<a class="btn btn-success btn-xs ' + editFlag + '" href="javascript:void(0)" onclick="$.operate.edit(\'' + row.id + '\')"><i class="fa fa-edit"></i>编辑</a> ');
      				actions.push('<a class="btn btn-danger btn-xs ' + removeFlag + '" href="javascript:void(0)" onclick="$.operate.remove(\'' + row.id + '\')"><i class="fa fa-remove"></i>删除</a>');
      				return actions.join('');
      			}
      		}]
      	};
      	$.table.init(options);
      });
    </script>

    <!-- 视频播放模态框 -->
    <div id="videoModal" class="modal fade" tabindex="-1" role="dialog">
      <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
          <div class="modal-header">
            <button
              type="button"
              class="close"
              data-dismiss="modal"
              aria-label="Close"
            >
              <span aria-hidden="true">&times;</span>
            </button>
            <h4 class="modal-title">视频播放</h4>
          </div>
          <div class="modal-body">
            <video id="videoPlayer" width="100%" height="400" controls>
              您的浏览器不支持视频播放。
            </video>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">
              关闭
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 引入学习时长记录器 -->
    <script th:src="@{/ruoyi/js/study-time-recorder.js}"></script>
    <script type="text/javascript">
      // 当前播放的视频ID
      let currentVideoId = null;

      // 统一的保存学习记录函数
      function saveStudyRecord() {
        if (!studyRecordSaved) {
          studyRecordSaved = true;
          endStudyRecord();
          console.log(
            "学习记录已保存 - 触发时间:",
            new Date().toLocaleTimeString()
          );
        } else {
          console.log("学习记录已经保存过了，跳过重复保存");
        }
      }

      // 监听页面卸载事件
      window.addEventListener("beforeunload", function (event) {
        console.log("beforeunload 事件触发");
        saveStudyRecord();
      });

      // 监听页面隐藏事件（标签页切换、最小化等）
      document.addEventListener("visibilitychange", function () {
        if (document.hidden) {
          console.log("页面被隐藏，visibilitychange 事件触发");
          saveStudyRecord();
        } else {
          console.log("页面重新可见，重置保存状态");
          // 页面重新可见时重置保存标志
          studyRecordSaved = false;
        }
      });

      // 监听窗口失去焦点
      window.addEventListener("blur", function () {
        console.log("窗口失去焦点，blur 事件触发");
        // 延时执行，避免短暂失焦就保存
        setTimeout(function () {
          if (!document.hasFocus()) {
            console.log("确认窗口失去焦点，保存学习记录");
            saveStudyRecord();
          }
        }, 1000);
      });

      // 监听浏览器页面关闭/刷新
      window.addEventListener("pagehide", function () {
        console.log("pagehide 事件触发");
        saveStudyRecord();
      });

      // 重置保存标志（当页面重新获得焦点时）
      window.addEventListener("focus", function () {
        if (studyRecordSaved) {
          studyRecordSaved = false;
          console.log("页面重新获得焦点，重置学习记录状态");
        }
      });
      // 播放视频
      function playVideo(videoSrc, videoId) {
        currentVideoId = videoId;
        $("#videoPlayer").attr("src", videoSrc);
        $("#videoModal").modal("show");
      }

      // 视频模态框关闭时的处理
      $("#videoModal").on("hidden.bs.modal", function () {
        if (currentVideoId && currentVideoId > 0) {
          // 结束具体视频的学习记录
          StudyTimeRecorder.end();
        }
        currentVideoId = null;
      });
    </script>
  </body>
</html>
